package cn.jiyun.user.controller;

import cn.jiyun.user.pojo.Users;
import cn.jiyun.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UserService userService;

    /**
     * 页面跳转
     */
    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page) {
        return page;
    }

    /**
     * 添加用户
     */
    @RequestMapping("/addUser")
    public String addUser(Users users) {
        this.userService.saveUser(users);
        return "ok";
    }

    /**
     * 查询全部用户
     */
    @RequestMapping("/listUser")
    public String listUser(Model model) {
        List<Users> list = this.userService.listUser();
        model.addAttribute("list", list);
        return "list";
    }

    @RequestMapping("/login")
    public String login(Model model, Users users, HttpSession session) {
        Users user = userService.login(users);
        if (user != null) {
            session.setAttribute("user", user);
            return "redirect:/users/listUser";
        }
        return "loginPage";
    }

    @RequestMapping("/findById")
    public String findById(Integer id, Model model) {
        Users users = userService.findById(id);
        model.addAttribute("users", users);
        return "updatePage";
    }

    /**
     * 删除
     */
    @RequestMapping("/deleteById")
    public String deleteById(Integer id, Model model) {
        userService.deleteById(id);
        List<Users> list = this.userService.listUser();
        model.addAttribute("list", list);
        return "list";
    }

    /**
     * 删除
     */
    @RequestMapping("/updateUser")
    public String updateUser(Users users,Model model){
        userService.updateUsers(users);
        List<Users> list = this.userService.listUser();
        model.addAttribute("list", list);
        return "list";
    }
}
